package com.example.devicemanage.controller;

import com.example.devicemanage.entity.Admin;
import com.example.devicemanage.service.inter.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@Controller
public class AdminController {

    @Autowired
    AdminService adminService;
    @RequestMapping(path = "/", method = RequestMethod.GET)
    String doGet(){
        return "login";
    }

    @RequestMapping(path = "/adminlogin", method = RequestMethod.POST)
        //获取请求参数方式3,直接使用原生的HttpServletRequest
       String login(HttpServletRequest httpServletRequest) {
        String  name = httpServletRequest.getParameter("name");
        String password = httpServletRequest.getParameter("password");
           Admin admin=new Admin();
       admin.setName(name);
       admin.setPassword(password);

        //调用service层验证数据
        boolean flag = adminService.login(admin);

        if(flag == true){ //登录成功
//            //设置域对象
//            //request域
//            httpServletRequest.setAttribute("str", userId);
//            //session域
//            httpServletRequest.getSession().setAttribute("str", userId);
//            //context域
//            httpServletRequest.getServletContext().setAttribute("str", userId);
           HttpSession session= httpServletRequest.getSession();
           session.setAttribute("name",name);

            //转发到index.jsp
            return "index";
        }
        else{
            httpServletRequest.setAttribute("loginResult", "登录失败");
            //登录失败返回到login.jsp
            return "login";
        }



    }


    @RequestMapping(path = "/exit_login", method = RequestMethod.GET)
    String exitLogin(HttpServletRequest httpServletRequest){
        HttpSession session=httpServletRequest.getSession();
        if(session.getAttribute("name")!=null){
            session.invalidate();
        }
        return "login";
    }

    @RequestMapping(path = "/welcome", method = RequestMethod.GET)
    String doWelcome(){
        return "welcome";
    }




}
